led1 = 3
led2 = 4
gpio.mode(led1, gpio.OUTPUT)
gpio.mode(led2, gpio.OUTPUT)
gpio.write(led1, gpio.HIGH);
gpio.write(led2, gpio.HIGH);

mac = string.gsub(wifi.sta.getmac(), ":", "")

-- mqtt_test.lua
function mqtt_connect()
    pub_topic = "mcu_to_pc/" .. mac
    sub_topic = "pc_to_mcu/" .. mac
    clientId = "clientId_mqtt_" .. mac
    print("connect mqtt " .. clientId)
    print(pub_topic)
    print(sub_topic)
    myClient = mqtt.Client(clientId, 120, "dc3", "dc3")
    myClient:connect("59.36.246.11", 18083, false, function(client)
        print("connected")
    end, function(client, reason)
        print("connect failed " .. reason)
        node.restart()
    end)
    myClient:lwt(pub_topic, "mcu is closed")
    myClient:on("connect", function(clinet)
        if (myClient:publish(pub_topic, "online", 0, 0)) then
            print("pc connected mcu")
        end
        if (myClient:subscribe(sub_topic, 0)) then
            print("subscribe is success.")

            gpio.write(led1, gpio.LOW);
            tmr.delay(50000)
            gpio.write(led1, gpio.HIGH);

            timer1 = tmr.create()
            timer1:register(60000, tmr.ALARM_AUTO, function()
                myClient:publish(pub_topic, "online", 0, 0)
            end)
            timer1:start()

        end
    end)
    myClient:on("offline", function(client)
        myClient:publish(pub_topic, "offline", 0, 0)
        node.restart()
    end)
    myClient:on("message", function(client, topic, message)
        print("get a message.\n")
        print(topic .. ":" .. message)
        if (message == "ON1") then
            gpio.write(led1, gpio.LOW);
            print("led1 on")
        elseif (message == "OFF1") then
            gpio.write(led1, gpio.HIGH);
            print("led1 off")
        elseif (message == "ON2") then
            gpio.write(led2, gpio.LOW);
            print("led2 on")
        elseif (message == "OFF2") then
            gpio.write(led2, gpio.HIGH);
            print("led2 off")
        end
    end)
end

mqtt_connect()
